<template>
  <basic-drawer
    :visible="visible"
    :title="title"
    ok-text="保存配置"
    :loading="saveLoading"
    @ok="handleSubmit"
    @open="handleBeforeOpen"
    @close="handleBeforeClose"
    @cancel="emits('update:visible', false)">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <a-form-item
        field="name"
        label="规则名称"
        hide-asterisk
        asterisk-position="end"
        required>
        <a-input
          v-model="formData.name"
          :max-length="20"
          class="!w-100"
          placeholder="请输入规则名称">
        </a-input>
      </a-form-item>
      <a-form-item
        label="匹配规则"
        asterisk-position="end"
        hide-asterisk
        required
        class="rule-help-item">
        <matching-rule-view
          ref="matchingView"
          v-model="ruleGroups"
          class="w-full"></matching-rule-view>
      </a-form-item>
      <a-form-item
        field="module_config.skip_module"
        label="执行策略"
        hide-asterisk
        asterisk-position="end"
        required
        class="skip-item">
        <template #label>
          <div class="flex flex-col">
            <span>执行策略</span>
            <span class="text-xs/5 text-5">
              规则生效时，跳过下面指定模块：
            </span>
          </div>
        </template>
        <a-checkbox-group v-model="formData.module_config.skip_module">
          <a-checkbox :value="1">自定义规则</a-checkbox>
          <a-checkbox :value="2">速率限制</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item
        v-if="list.length > 0"
        field="order"
        label="执行优先级"
        hide-asterisk
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <a-select
            v-model="formData.order"
            placeholder="请选择执行优先级"
            class="!w-100"
            :options="getOption"
            @change="handleChange" />
          <a-form-item
            v-if="formData.order === A_EXECUTION_PRIORITY.CUSTOM"
            field="priority"
            hide-label
            asterisk-position="end"
            class="!mb-0 mt-2"
            required>
            <a-select
              v-model="formData.priority"
              class="w-[336px]"
              placeholder="优先触发创建的规则，再触发选择的规则">
              <a-option
                v-for="item in props?.record?.id ? filterList : list"
                :key="item.id"
                :label="item.name"
                :value="item.priority" />
            </a-select>
          </a-form-item>
          <span
            v-if="formData.order === A_EXECUTION_PRIORITY.CUSTOM"
            class="text-5 text-xs/5"
            >在此规则前执行。</span
          >
        </section>
      </a-form-item>
    </a-form>
  </basic-drawer>
</template>
<script lang="ts" setup>
import type { WafListItem } from '@/apis/model/waf'
import {
  addApiWafApi,
  getApiWafApi,
  getApiWafQueryApi,
  updateApiWafApi
} from '@/apis/modules/waf'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import type { IMatchingGroup } from '@/components/MatchingRule/types'
import { getFieldValue } from '@/components/MatchingRule/utils'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { v4 as uuidV4 } from 'uuid'
interface IProps {
  visible: boolean
  record?: any
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false
})
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}
const emits = defineEmits<IEmits>()
const title = computed(() => (props?.record?.id ? '编辑规则' : '创建规则'))
const formRef = ref<FormInstance>()
const matchingView = ref()
const formData = ref({
  name: '',
  scope: 3,
  action: 2,
  module: 3,
  order: undefined,
  priority: undefined,
  module_config: { skip_module: [] }
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    name: [
      {
        required: true,
        message: '请输入规则名称'
      }
    ],
    'module_config.skip_module': [
      {
        required: true,
        message: '请选择执行动作'
      }
    ],
    order: [
      {
        required: true,
        message: '请选择执行优先级'
      }
    ],
    priority: [
      {
        required: true,
        message: '请选择自定义规则'
      }
    ]
  }
})
const ruleGroups = ref<IMatchingGroup[]>([
  {
    uuid: uuidV4(),
    rules: [
      {
        uuid: uuidV4(),
        field: '',
        operator: '',
        value: '',
        custom_field: ''
      }
    ]
  }
])

const handleBeforeOpen = async () => {
  await run()
  if (props.record) request({ id: props.record?.id })
}
const handleBeforeClose = async () => {
  await formRef.value?.resetFields()
  matchingView.value?.reset()
  emits('update:visible', false)
}
const params = ref<CloudFilterBarState>({
  order: 'asc',
  sort: 'priority',
  scope: 3,
  module: 3
})
const list = ref<WafListItem[]>([])
const filterList = ref<WafListItem[]>([])
const { run, pagination } = useListRequest(getApiWafQueryApi, {
  params,
  immediate: false,
  async afterFn(res) {
    await nextTick()
    list.value = res.list || []
    if (!list.value.length) return
    filterList.value = res.list.filter((item) => item.id !== props?.record?.id)
  }
})
pagination.value.pageSize = 1000
const getOption = computed(() => {
  if (props.record?.id) {
    return list.value.length > 2 ? priorityOptions : priorityOptions.slice(0, 2)
  } else {
    return list.value.length > 1 ? priorityOptions : priorityOptions.slice(0, 2)
  }
})
const prePriority = ref(0)
const handleChange = (val) => {
  if (val === 2) {
    if (prePriority.value === list.value[0].priority) {
      formData.value.priority = prePriority.value + 1
    } else if (
      prePriority.value === list.value[list.value.length - 1].priority
    ) {
      formData.value.priority = prePriority.value - 1
    }
  }
}
const { request } = useRequest(getApiWafApi, {
  success(res) {
    Object.assign(formData.value, res)
    prePriority.value = res.priority!
    ruleGroups.value[0].rules = res.conditions.map((item) => {
      return {
        uuid: uuidV4(),
        ...item,
        value:
          getFieldValue(item)!.count > 1 ? item.value : item.value.toString()
      }
    })
    if (list.value.length) {
      if (list.value.length === 1)
        formData.value.order = formData.value.priority
      const priorityArr = list.value.map((item: WafListItem) => item.priority!)
      const min = Math.min(...priorityArr)
      const max = Math.max(...priorityArr)
      switch (+formData.value.priority!) {
        case min:
          formData.value.order = A_EXECUTION_PRIORITY.FIRST
          break
        case max:
          formData.value.order = A_EXECUTION_PRIORITY.LAST
          break
        default:
          formData.value.order = A_EXECUTION_PRIORITY.CUSTOM
      }
    } else {
      formData.value.order = A_EXECUTION_PRIORITY.FIRST
    }
    if (formData.value.order === A_EXECUTION_PRIORITY.CUSTOM) {
      formData.value.priority = formData.value.priority + 1
    } else {
      formData.value.priority = formData.value.priority!
    }
  }
})
const saveLoading = ref(false)
async function handleSubmit() {
  const error = await formRef.value?.validate()
  const error1 = await matchingView.value.validate()
  if (error || !error1) return false
  saveLoading.value = true
  const data: any = {
    ...formData.value,
    conditions: ruleGroups.value[0].rules.map((item) => {
      return {
        ...item,
        value: !Array.isArray(item.value)
          ? item.value
            ? [item.value]
            : []
          : item.value.filter(Boolean)
      }
    }),
    id: props.record ? props.record?.id : undefined
  }
  if (formData.value?.order === A_EXECUTION_PRIORITY.FIRST) {
    data.priority = 1
  } else if (formData.value?.order === A_EXECUTION_PRIORITY.LAST) {
    data.priority = 0
  } else {
    data.priority = formData?.value?.priority
  }
  const api_path = props.record ? updateApiWafApi : addApiWafApi
  api_path(data)
    .then(() => {
      ToastUtils.success('操作成功')
      emits('update:visible', false)
      emits('refresh')
    })
    .finally(() => (saveLoading.value = false))
}
</script>

<style lang="less" scoped>
// :deep(.arco-form-item-label-col) {
//   @apply mb-0;
// }
</style>
